#include "Sphere.h"
#include <memory>
#include <SEMath/Shapes/Loader/ShapeLoader.h>
#include <limits>

namespace SEngine
{    
    template<>
    std::unique_ptr<Sphere> ShapeLoader::CreateImpl<Sphere>() {
        glm::vec3 sum{0.0f};
        for (auto & vertex : m_vertices) {
            sum += vertex;
        }
        glm::vec3 pos{0.0f};
        if (!m_vertices.empty())
            pos = sum / (float)m_vertices.size();
        float radius = 0;
        for (auto & vertex : m_vertices) {
            radius = glm::max(radius, glm::distance(vertex, pos));
        }
        return std::make_unique<Sphere>(pos, radius);
    }
    
    void Sphere::Transform(glm::mat4 matrix)
    {
        glm::vec3 point = matrix * glm::vec4(m_pos + glm::vec3{1.0f, 0.0f, 0.0f} * m_radius, 1.0f);
        m_pos = matrix * glm::vec4{m_pos, 1.0f};
        m_radius = glm::distance(m_pos, point);
    }
} // namespace SEngine

